<template>
	<view class="container">
		<!-- 购买须知弹窗 -->
		<div class="curtains" v-if="isShows" @click="showPolicys"></div>
		<view class="ticket-details" v-show="isShows">
			<view class="ticket-details-title">购买须知</view>
			<div class="ticket-details-content" v-html="processedHtml"></div>
			<button class="registers" @click="showPolicys">关闭</button>
		</view>

		<!-- 顶部导航 -->
		<div class="top">
			<div class="top_button">
				<div class="return" @click="returnPage">
					<image :src="imageBaseUrl + '/img/return.png'"></image>
				</div>
				<div class="line"></div>
				<div class="homepage" @click="goHome">
					<image :src="imageBaseUrl + '/img/home.png'"></image>
				</div>
			</div>
			<div>提交订单</div>
		</div>

		<!-- 门票标题 -->
		<text class="hthree">{{ ticketInfo.name }}</text>

		<!-- 选择日期 -->
		<view class="date">
			<view class="optionDate">
				<text class="title">选择日期</text>
				<image v-show="dateWarning" :src="imageBaseUrl + '/img/warn.png'"></image>
				<text v-show="dateWarning" style="color: red;">
					请先选择使用日期
				</text>
			</view>
			<view class="block">
				<scroll-view class="datePicker" scroll-x="true" :scroll-left="scrollLeftValue" @scroll="onScroll"
					scroll-with-animation>
					<view class="datePickers">
						<view v-for="(item, index) in dates" :key="index"
							:class="['dateItem', selectedDate === item.date ? 'selected' : '', item.isToday ? 'disabled' : '']"
							@click="!item.isToday && handleSelectDate(item.date)">
							<text class="dateP">{{ item.date }}</text>
							<text class="dateSpan">￥{{ ticketInfo.current_price }}</text>
						</view>
					</view>
				</scroll-view>
				<view class="blockTwo" @click="scrollToEnd">
					<text class="orange">￥{{ ticketInfo.current_price * 100 / 100 }}起</text>
					<view>
						<div style="width: 40px; height: 18px; font-size: 14px;">更多日期</div>
					</view>
					<div class="right">
						<image :src="imageBaseUrl + '/img/right.png'"></image>
					</div>
				</view>
			</view>
			<view class="bot">
				<text>无序退票 | 随时退 |</text>
				<text style="color: #e55b5b;">需携带游客身份证</text>
				<view @click="showPolicys" style="display: flex;align-items: center;">
					<text>购买须知</text>
					<div class="btn">
						<image :src="imageBaseUrl + '/img/right.png'"></image>
					</div>
				</view>
			</view>
		</view>



		<!-- 选择数量 -->
		<view class="number">
			<view class="num">
				<text class="title">选择数量</text>
				<view class="pedometer">
					<view class="reduce" @click="subtract">-</view>
					<view class="numbers"><text id="num">{{ quantity }}</text></view>
					<view class="reduce" @click="add">+</view>
				</view>
			</view>
			<view class="astrict">
				<text>每单限购1张，同一证件当天限购一张</text>
			</view>
			<view class="tourist">
				<text class="title">游客信息</text>
				<view class="disFont">
					<view class="font"><text>姓 名：</text></view>
					<text>{{ userInfo.nickname }}</text>
				</view>
				<view class="disFont">
					<view class="font"><text>身份证号：</text></view>
					<text id="idNum">暂无数据</text>
				</view>
				<view class="disFont">
					<view class="font"><text>手 机 号：</text></view>
					<text id="tel">{{ userInfo.tel }}</text>
				</view>
			</view>
		</view>

		<!-- 提交订单 -->
		<view class="bottom">
			<view class="allNum">
				<text style="font-size: 12px;">总价</text>
				<text style="font-size: 10px; color: #d43079;">￥</text>
				<text style="font-size: 17px; color: #d43079;" id="eight">{{ totalPrice }}</text>
			</view>
			<view class="subOrder" @click="handleSubmitOrder">
				<text>提交订单</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import config from '../../config/index.js';

const imageBaseUrl = config.image;//图片路径
const showAlert = ref(false); // 购买须知弹窗显示状态
const selectedDate = ref(null); // 选择的日期
const quantity = ref(1); // 购买数量
const scrollLeftValue = ref(0); // 滚动位置
const maxScrollLeft = ref(0); // 滚动最大位置
const today = new Date(); // 当前日期
const currentIndex = ref(0); // 当前索引
const itemWidth = ref(0); // 单个日期项宽度（含边框）
const isShows = ref(false); // 显示隐藏
const skynum = ref(3); // 初始显示3天
const processedHtml = ref(''); // html数据
const dateWarning = ref(false); // 日期选择警告

// 生成日期数据函数 - 修复isToday判断逻辑
const generateDates = (days = skynum.value) => {
	const dates = [];// 日期数据
	const todayStr = today.toISOString().split('T')[0]; // 获取今天的YYYY-MM-DD格式

	for (let i = 0; i < days; i++) {
		const date = new Date(today);// 创建一个日期对象
		date.setDate(today.getDate() + i);//  设置日期
		const year = date.getFullYear();//  获取年份
		const month = String(date.getMonth() + 1).padStart(2, '0');// 获取月份，并补全为两位
		const day = String(date.getDate()).padStart(2, '0');// 获取日期，并补全为两位

		// 修复：根据日期比较判断是否为今天，而非索引
		const isToday = `${year}-${month}-${day}` === todayStr;

		dates.push({
			date: `${year}-${month}-${day}`,
			price: 100, // 示例价格
			isToday
		});
	}
	return dates;
};

// 初始数据
const dates = ref(generateDates(skynum.value));
const userInfo = ref({
	nickname: '用户昵称',
	tel: '1234567890',
	code: ''
});
//  获取门票信息
const ticketInfo = ref({
	name: '门票名称',
	current_price: 80,
	id: ''
});

// 计算总价 - 优化精度处理
const totalPrice = ref((quantity.value * ticketInfo.value.current_price).toFixed(2));

// 显示/关闭购买须知
const handleShowAlert = () => {
	showAlert.value = true;
};
//  关闭购买须知
const handleCloseAlert = () => {
	showAlert.value = false;
};

// 导航操作
const returnPage = () => {
	uni.navigateBack({
		delta: 1
	});
};
//  跳转首页
const goHome = () => {
	uni.navigateTo({
		url: '/pages/home/home'
	});
};

// 选择日期
const handleSelectDate = (date) => {
	selectedDate.value = date;
	dateWarning.value = false; // 选择日期后清除警告
};

// 数量操作
const subtract = () => {
	if (quantity.value > 1) {
		quantity.value--;
		totalPrice.value = (quantity.value * ticketInfo.value.current_price).toFixed(2);
	}
};
// 数量操作
const add = () => {
	quantity.value++;
	totalPrice.value = (quantity.value * ticketInfo.value.current_price).toFixed(2);
};

// 提交订单
const handleSubmitOrder = () => {
	if (!selectedDate.value) {
		dateWarning.value = true;
		return; // 不自动清除警告，直到用户选择日期
	}
	// 构建订单数据
	const data = {
		scenic_id: 3,
		ticketing_id: ticketInfo.value.id,
		user_id: userInfo.value.id,
		time: selectedDate.value,
		status: 1,
		number: quantity.value,
		total_price: totalPrice.value,
		name: ticketInfo.value.name,
	};

	console.log('提交订单:', data);
	uni.setStorageSync('orderInfo', data);
	uni.navigateTo({
		url: '/pages/pay/pay'
	});
};

// 计算最大滚动距离 - 修复空值问题
const calculateMaxScrollLeft = () => {
	nextTick(() => {
		const query = uni.createSelectorQuery();
		query.select('.datePicker').boundingClientRect(container => {
			if (!container) return; // 防御性检查
			query.selectAll('.dateItem').boundingClientRect(items => {
				if (!items || items.length === 0) {
					console.warn('未找到日期项元素');
					return;
				}
				itemWidth.value = items[0].width; // 获取元素宽度

				let totalWidth = 0;
				items.forEach((item, index) => {
					totalWidth += item.width;
					if (index < items.length - 1) {
						totalWidth += 10; // flex gap 间距
					}
				});
				maxScrollLeft.value = Math.max(0, totalWidth - container.width);
			}).exec();
		}).exec();
	});
};

// 点击更多日期
const scrollToEnd = () => {
	skynum.value = 6; // 显示更多日期
	dates.value = generateDates(skynum.value);

	nextTick(() => {
		calculateMaxScrollLeft(); // 重新计算滚动位置
		scrollLeftValue.value = maxScrollLeft.value; // 滚动到最右侧
	});
};

// 显示/隐藏购买须知
const showPolicys = () => {
	isShows.value = !isShows.value;
};

// 监听滚动事件
const onScroll = (e) => {
	if (itemWidth.value > 0) {
		currentIndex.value = Math.floor(e.detail.scrollLeft / itemWidth.value);
	}
};

// 组件挂载后初始化
onMounted(() => {
	// 等待DOM渲染完成后计算滚动位置
	nextTick(() => {
		calculateMaxScrollLeft();
	});

	// 窗口大小变化时重新计算
	uni.onWindowResize(() => {
		calculateMaxScrollLeft();
	});

	// 获取本地存储数据 - 添加空值检查
	try {
		const target = uni.getStorageSync('target') || {};
		ticketInfo.value = target;
		if (ticketInfo.value.id == 1){
			ticketInfo.value.name =  '[成人]门票+五龙山游乐园票';
		}
		console.log(ticketInfo.value);
		if (target.current_price) {
			totalPrice.value = (quantity.value * target.current_price).toFixed(2);
		}
		// 修复字段名拼写错误: deatils -> details
		processedHtml.value = target.deatils?.replace(/&nbsp;/g, ' ') || '';
	} catch (e) {
		console.error('获取门票信息失败:', e);
	}

	try {
		const token = uni.getStorageSync('token') || {};
		userInfo.value = token;
	} catch (e) {
		console.error('获取用户信息失败:', e);
	}
});
</script>

<style scoped>
.registers {
	width: 90%;
	height: 35px;
	background-color: #FF8D1A;
	border-radius: 35px;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #ffffff;
	margin-top: 20px;
	font-size: 15px;
	position: fixed;
	bottom: 20px;
	left: 5%;
}

.allNum {
	display: flex;
	color: #e55b5b;
	align-items: center;
	margin-left: 10px;
}

.reduce {
	width: 25px;
	height: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 2px;
	border: 1px #e3e3e3 solid;
}

.btn image {
	width: 15px;
	height: 15px;
	padding-top: 5px;
}

.curtains {
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
	height: 100vh;
	background-color: rgba(134, 134, 134, 0.475);
	z-index: 3;
}

.ticket-details-title {
	font-size: 18px;
	width: 100%;
	padding: 10px;
	text-align: center;
}

.ticket-details-content {
	width: 90%;
	margin-left: 5%;
	margin-bottom: 80px;
}

.ticket-details {
	width: 100vw;
	height: 500px;
	border-radius: 15px 15px 0 0;
	overflow-y: auto;
	position: fixed;
	bottom: 0;
	background-color: white;
	z-index: 999;
}

.title {
	font-size: 18px;
}

.container {
	width: 100%;
	height: 100%;
}

.line {
	width: 1%;
	background-color: #8a8a8a;
	height: 70%;
	margin-top: 5%;
}

.return {
	width: 49.5%;
	height: 100%;
	text-align: center;
	line-height: 25px;
}

.return image {
	width: 20px;
	margin-top: 2px;
	height: 20px;
}

.homepage {
	width: 49.5%;
	height: 100%;
	text-align: center;
	line-height: 25px;
}

.homepage image {
	width: 18px;
	margin-top: 3px;
	height: 18px;
}

.top_button {
	width: 70px;
	height: 25px;
	display: flex;
	border-radius: 15px;
	margin-left: 20px;
	margin-right: 20%;
	border: 1px solid rgb(192, 192, 192);
}

.right image {
	width: 15px;
	height: 15px;
	margin-left: -10px;
}

.right {
	margin-top: 10px;
}

.top {
	width: 100%;
	height: 50px;
	margin-top: 30px;
	border-bottom: 1px solid rgb(203, 203, 203);
	background-color: rgb(255, 255, 255);
	position: relative;
	color: #8a8a8a;
	display: flex;
	align-items: center;
}

.hthree {
	font-size: 20px;
	margin-left: 20px;
	height: 50px;
	width: 90%;
	text-wrap: nowrap;
	line-height: 50px;
}

.date {
	margin-top: 10px;
	width: 96%;
	height: 150px;
	background-color: #fff7f5;
	margin-left: 2%;
}

.optionDate {
	display: flex;
	align-items: center;
	line-height: 30px;
}

.optionDate image {
	width: 20px;
	height: 20px;
	margin-left: 5px;
}

.optionDate text {
	color: #595959;
	margin: 8px 5px 10px 10px;
}

.optionDate text:nth-child(2) {
	margin-left: 5px;
	font-size: 13px;
	color: #e55b5b;
}

.block {
	width: 96%;
	margin-left: 2%;
	display: flex;
}

.datePicker {
	width: 100%;
	font-size: 14px;
	margin-left: 1%;
	white-space: nowrap;
	overflow-x: auto;
	scrollbar-width: none;
	-ms-overflow-style: none;
}

.datePicker::-webkit-scrollbar {
	display: none;
}

.datePickers {
	display: flex;
	flex-wrap: nowrap;
	gap: 10px;
	padding: 5px 0;
}

.dateItem {
	flex: 0 0 auto;
	width: 90px;
	height: 50px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	border-radius: 3px;
	border: 1px #d1d1d1 solid;
	background-color: #ffffff;
	box-sizing: border-box;
}

.selected {
	background-color: #eeeeee;
}

.dateP {
	font-size: 14px;
	color: #555555;
	margin: 0 5px;
}

.dateSpan {
	color: #da322c;
	font-size: 14px;
	margin-left: 5px;
}

.blockTwo {
	width: 45px;
	height: 45px;
	padding-top: 5px;
	font-size: 12px;
	color: #636363;
	position: relative;
	display: flex;
	margin-left: 5px;
	margin-right: 5px;
	margin-top: 5px;
	border-radius: 3px;
	border: 1px #d1d1d1 solid;
	background-color: #ffffff;
}

.orange {
	text-align: center;
	width: 40px;
	height: 20px;
	position: absolute;
	top: -12px;
	color: #ffffff;
	font-size: 9px;
	display: flex;
	justify-content: center;
	align-items: center;
	white-space: nowrap;
	left: 0;
	border-radius: 10px 0 10px 0;
	background-color: #ff8d1a;
}

.bot {
	width: 96%;
	margin-left: 2%;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-top: 5px;
	background-color: #fff9d9;
}

.bot text {
	font-size: 13px;
	color: #636363;
}

.number {
	width: 92%;
	margin-left: 4%;
	height: 150px;
	margin-top: 20px;
}

.num {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-right: 15px;
}

.pedometer {
	width: 90px;
	height: auto;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.astrict {
	width: 94%;
	height: 25px;
	margin: 10px 0;
	margin-left: 2%;
	display: flex;
	align-items: center;
	background-color: #ebebeb;
	border-radius: 5px;
}

.astrict text {
	font-size: 13px;
	margin-left: 10px;
	color: #636363;
}

.tourist {
	margin-top: 20px;
}

.font {
	font-size: 14px;
	width: 90px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.disFont {
	display: flex;
	align-items: center;
	height: 30px;
	color: #636363;
	margin-left: 5px;
	margin-top: 20px;
	display: flex;
}

.disFont text {
	font-size: 14px;
	margin-left: 5px;
}

.bottom {
	width: 100%;
	height: 45px;
	position: absolute;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-top: 1px #e7e7e7 solid;
}

.subOrder {
	height: 35px;
	background-color: #ff5733;
	color: #ffffff;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 20px;
	padding: 0 25px;
	margin-right: 15px;
}

.alert {
	width: 100%;
	min-height: 100vh;
	position: absolute;
	z-index: 1;
	background-color: rgba(0, 0, 0, 0.4);
}

.alertOne {
	width: 100%;
	height: auto;
	position: absolute;
	bottom: 0;
	padding: 10px 0;
	border-radius: 10px 10px 0 0;
	background-color: #ffffff;
}

.alertOne text {
	margin-left: 15px;
	margin-right: 10px;
	font-size: 13px;
	line-height: 14px;
	display: flex;
	justify-content: left;
	align-items: baseline;
}

.close {
	width: 96%;
	height: 40px;
	color: #ffffff;
	margin-left: 2%;
	display: flex;
	margin: 10px 5;
	justify-content: center;
	align-items: center;
	border-radius: 20px;
	margin-top: 5px;
	background-color: #ff8d1a;
}

/* 禁用样式 */
.dateItem.disabled {
	cursor: not-allowed;
	background-color: #efefef;
	border-color: #e0e0e0;
}

.dateItem.disabled .dateP,
.dateItem.disabled .dateSpan {
	color: #999;
}
</style>